package com.haikesi.api.subscribertable.service.impl;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.haikesi.api.device.dao.DeviceDao;
import com.haikesi.api.device.domain.po.DevicePO;
import com.haikesi.api.subscribertable.domain.vo.*;
import com.haikesi.util.ButlerApiUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.haikesi.api.base.Constants;
import com.haikesi.api.base.Error;
import com.haikesi.api.base.ErrorTools;
import com.haikesi.api.base.RedisUtils;
import com.haikesi.api.base.Type;
import com.haikesi.api.subscribertable.dao.SubscriberTableDao;
import com.haikesi.api.subscribertable.domain.po.SubscriberTablePo;
import com.haikesi.api.subscribertable.service.ISubscriberTableService;
import com.haikesi.exception.BusinessException;
import com.haikesi.util.ApcosApiUtils;

import tk.mybatis.mapper.entity.Example;

/**
 * @version V1.0
 * @ClassName: SubscriberTableServiceImpl
 * @Description: TODO(用一句话描述该文件做什么)
 * @author: zqy
 * @date: 2019年5月15日 下午5:34:39
 * @Copyright: 2019 重庆海克斯科技有限公司.
 * 注意：本内容仅限于重庆海克斯科技有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
@Transactional
public class SubscriberTableServiceImpl implements ISubscriberTableService {


    private static Log log = LogFactory.getLog(SubscriberTableServiceImpl.class);
    @Autowired
    private SubscriberTableDao subscriberTableDao;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    DeviceDao deviceDao;

    @Override
    public List<SubscriberTableVo> getList(SubscriberTableSearchVo subscriberTableSearchVo) {
        SubscriberTablePo po = new SubscriberTablePo();
        if(po.getUser()==null){
            subscriberTableSearchVo.setOrganizationId("");
            return subscriberTableDao.getList(subscriberTableSearchVo);
        }
        subscriberTableSearchVo.setOrganizationId(po.getUser().getOrganizationId());
        if(po.getUser().getIsAdmin()==1){
            subscriberTableSearchVo.setOrganizationId("999");
        }

        List<SubscriberTableVo> list = subscriberTableDao.getList(subscriberTableSearchVo);
        return list;

    }

    @Override
    public void create(SubscriberTableSaveVo subscriberTableSaveVo) {
        SubscriberTablePo subscriberTablePo = new SubscriberTablePo();
        BeanUtils.copyProperties(subscriberTableSaveVo, subscriberTablePo);
        if (StringUtils.isBlank(subscriberTableSaveVo.getSubscriberNumber())) {
            // 如果订阅账号为空 则需要在大管家创建授权账号
            String account = ButlerApiUtils.createAccount(subscriberTableSaveVo.getPassword(), subscriberTableSaveVo.getUserName(), subscriberTableSaveVo.getUserPhone(), subscriberTableSaveVo.getIdNo(), subscriberTableSaveVo.getGender(), subscriberTableSaveVo.getEmail(), subscriberTableSaveVo.getAreaCode1(), subscriberTableSaveVo.getAreaCode2(), subscriberTableSaveVo.getAreaCode3());
            if (StringUtils.isBlank(account)) {
                throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "大管家授权账号添加失败")));
            }
            subscriberTablePo.setSubscriberState(Constants.SUBSCRIBER_STATE_2);
            subscriberTablePo.setSubscriberType(Constants.SUBSCRIBER_TYPE_2);
            subscriberTablePo.setSubscriberNumber(account);
        } else {
            // 如果订阅账号存在 则需要在本地平台校验参数
            Example example = new Example(SubscriberTablePo.class);
            example.and().andEqualTo("subscriberNumber", subscriberTablePo.getSubscriberNumber());
            List<SubscriberTablePo> list = subscriberTableDao.selectByExample(example);
            if (!list.isEmpty()) {
                throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "订阅账号已存在")));
            }
            subscriberTablePo.setSubscriberState(Constants.SUBSCRIBER_STATE_0);
            subscriberTablePo.setSubscriberType(Constants.SUBSCRIBER_TYPE_1);
        }

        subscriberTablePo.preInsert();
        int i = subscriberTableDao.insertSelective(subscriberTablePo);
        if (i == Constants.SQL_RETUN_SUCCESS) {
            new BusinessException(Type.EXCEPTION_FAIL);
        }
    }

    @Override
    public void update(SubscriberTableUpdateVo subscriberTableUpdateVo) {
        SubscriberTablePo subscriberTablePo = new SubscriberTablePo();
        BeanUtils.copyProperties(subscriberTableUpdateVo, subscriberTablePo);
        SubscriberTablePo po = subscriberTableDao.selectByPrimaryKey(subscriberTablePo.getId());
        Example example = new Example(SubscriberTablePo.class);
        example.and().andEqualTo("subscriberNumber", subscriberTableUpdateVo.getSubscriberNumber());
        SubscriberTablePo list = subscriberTableDao.selectOneByExample(example);
        if (po == null) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("id", "账号不存在")));
        }
        if (list != null && !po.getSubscriberNumber().equals(list.getSubscriberNumber())) {
            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "订阅账号已存在")));
        }
        if (!po.getSubscriberNumber().equals(subscriberTableUpdateVo.getSubscriberNumber()) && (po.getSubscriberState() == 1 || po.getSubscriberState() == 2)) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberState", "只能修改未发送订阅或者订阅失败的账号")));
        }
        if (po.getSubscriberType() == Constants.SUBSCRIBER_STATE_2) {
            String resultCode = ButlerApiUtils.updateAccount(po.getSubscriberNumber(), subscriberTablePo.getPassword(), subscriberTablePo.getUserName(), subscriberTablePo.getUserPhone(), subscriberTablePo.getIdNo(), subscriberTablePo.getGender(), subscriberTablePo.getEmail(), subscriberTablePo.getAreaCode1(), subscriberTablePo.getAreaCode2(), subscriberTablePo.getAreaCode3());
            if (!"0000".equals(resultCode)) {
                throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "大管家授权账号失败")));
            }
        }
        subscriberTablePo.preUpdate();
        subscriberTablePo.setSubscriberState(po.getSubscriberState());
        int i = subscriberTableDao.updateByPrimaryKeySelective(subscriberTablePo);
        if (i == Constants.SQL_RETUN_SUCCESS) {
            throw new BusinessException(Type.EXCEPTION_FAIL);
        }
    }

    @Override
    public void delete(String id) {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException(Type.FORMAT_EXCEPTION);
        }
        SubscriberTablePo po = subscriberTableDao.selectByPrimaryKey(id);
        if (po == null) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("id", "账号不存在")));
        }
        if (po.getSubscriberState() == 1 || po.getSubscriberState() == 2) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberState", "只能删除未发送订阅或者订阅失败的账号")));
        }

        if (po.getSubscriberType() == Constants.SUBSCRIBER_STATE_2) {
            String resultCode = ButlerApiUtils.deleteAccount(po.getSubscriberNumber());
            if (!"0000".equals(resultCode)) {
                throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "管家授删除账号失败")));
            }
        }
        int i = subscriberTableDao.deleteByPrimaryKey(id);
        if (i == Constants.SQL_RETUN_SUCCESS) {
            throw new BusinessException(Type.EXCEPTION_FAIL);
        }
    }

    @Override
    public void subscriber(String subscriberNumber) {
        if (StringUtils.isBlank(subscriberNumber)) {
            throw new BusinessException(Type.FORMAT_EXCEPTION);
        }
        Example example = new Example(SubscriberTablePo.class);
        example.and().andEqualTo("subscriberNumber", subscriberNumber);
        SubscriberTablePo list = subscriberTableDao.selectOneByExample(example);
        if (StringUtils.isBlank(redisUtils.get(Constants.SERVICE_KEY))) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("SERVICE_KEY", "请先配置第三方唯一标识")));
        }
        if (StringUtils.isBlank(redisUtils.get(Constants.SERVICE_ID))) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("SERVICE_ID", "请先配置唯一标识对应的 key")));
        }
        if (StringUtils.isBlank(redisUtils.get(Constants.SERVICE_BACK_URL))) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("SERVICE_BACK_URL", "请先配置回调 URI")));
        }
        if (list == null) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "订阅账号不存在")));
        }
        if (list.getSubscriberState() == 1 || list.getSubscriberState() == 2) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberState", "只能订阅未发送订阅或者订阅失败的账号")));
        }
        /**
         * 大管家账号不需要订阅
         */
        if (list.getSubscriberType() == Constants.SUBSCRIBER_STATE_2) {
            throw new BusinessException(Type.NOT_FOUND_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "大管家账号不需要订阅")));
        }
        String subscribe = ApcosApiUtils.subscribe(subscriberNumber);
        if ("0001".equals(subscribe)) {
            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "【出现异常或者被订阅账号非法(不存在)】 操作失败")));
        }
        if ("0003".equals(subscribe)) {
            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "【重复订阅】 操作失败")));
        }
        if (StringUtils.isBlank(subscribe)) {
            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "为空参数校验失败")));
        }
        if ("0000".equals(subscribe)) {
            int i = subscriberTableDao.updateSubscribe(subscriberNumber);
            if (i == Constants.SQL_RETUN_SUCCESS) {
                throw new BusinessException(Type.EXCEPTION_FAIL);
            }
        }

    }

    @Override
    public void bindDevice(SubscriberBindDeviceVo bindDeviceVo) {

        Example example = new Example(SubscriberTablePo.class);
        example.and().andEqualTo("subscriberNumber", bindDeviceVo.getAccount());
        SubscriberTablePo subscriberTablePo = subscriberTableDao.selectOneByExample(example);
        if (subscriberTablePo==null) {
            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("subscriberNumber", "订阅账号不已存在")));
        }

        String result = ButlerApiUtils.bindDevice(bindDeviceVo.getAccount(), bindDeviceVo.getSerial_num(), bindDeviceVo.getGenuine_code());
//        if (StringUtils.isBlank(result)) {
//            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("SubscriberBindDeviceVo", "大管家设备绑定失败")));
//        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        DevicePO po =new DevicePO();
        Example sexample = new Example(DevicePO.class);
        sexample.and().andEqualTo("deviceSubscriberNumber", bindDeviceVo.getAccount()).andEqualTo("deviceMac",jsonObject.get("deviceMac").toString());
        List<DevicePO> list=deviceDao.selectByExample(sexample);
        if(list==null||list.size()==0){
            po.setDeviceMac(jsonObject.get("deviceMac").toString());
            po.setSerialNum(jsonObject.get("serialNum").toString());
            po.setProductCode(jsonObject.get("productCode").toString());
            po.setDeviceName(jsonObject.get("deviceName").toString());
            po.setDeviceAlias(po.getDeviceName());
            po.setOrganizationId(subscriberTablePo.getOrganizationId());
            po.setDeviceSubscriberId(subscriberTablePo.getId());
            po.setDeviceSubscriberNumber(subscriberTablePo.getSubscriberNumber());
            po.preInsert();
            deviceDao.insertSelective(po);
        }


    }

    @Override
    public void unbindDevice(SubscriberBindDeviceVo bindDeviceVo) {
        String result = ButlerApiUtils.unbindDevice(bindDeviceVo.getAccount(), bindDeviceVo.getSerial_num());
//        if (!"0000".equals(result)) {
//            throw new BusinessException(Type.EXIST_ERROR, ErrorTools.ErrorAsArrayList(new Error("SubscriberBindDeviceVo", "解绑设备失败")));
//        }
        Example example = new Example(DevicePO.class);
        example.and().andEqualTo("deviceSubscriberNumber", bindDeviceVo.getAccount()).andEqualTo("serialNum",bindDeviceVo.getSerial_num());
        deviceDao.deleteByExample(example);
    }

    @Override
    public List<SubscriberTableVo> getSmhlist() {
        List<SubscriberTableVo> list = subscriberTableDao.getSmhlist();
        return list;
    }

}
